package com.gc.cscott.run;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.gc.cscott.domain.Executable;
import com.google.common.base.Joiner;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.FilenameUtils;

/**
 *
 * @author root
 */
public class Executor {
    private static final Logger log = Logger.getLogger(Executor.class.getSimpleName());
    public Process runExecutable(Executable executable, List<String> commandPattern, File workDir) throws IOException {
        Preconditions.checkNotNull(executable);
        Preconditions.checkArgument(workDir.isDirectory());

        
        ImmutableList.Builder<String> commandBuilder = ImmutableList.<String>builder();
        String pathToFile = executable.getExecutableFilePath().getAbsolutePath();
        String fileName = FilenameUtils.getBaseName(pathToFile);
        String fileNameExt = FilenameUtils.getName(pathToFile);
        String fileExt = FilenameUtils.getExtension(pathToFile);
        String fileDir = executable.getExecutableFilePath().getParentFile().getAbsolutePath();
        for(String argument:commandPattern){
            commandBuilder.add(argument
                    .replace("{FILE_NAME}", fileName)
                    .replace("{FILE_NAME_EXT}", fileNameExt)
                    .replace("{FILE_EXT}", fileExt)
                    .replace("{FILE_DIR}", fileDir)
                    .replace("{PATH_TO_FILE}", pathToFile));
        }
        List<String> command = commandBuilder.build();
        log.log(Level.INFO, "exec {0}", Joiner.on(" ").join(command));
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        processBuilder.directory(workDir);
        return processBuilder.start();
    }
}
